<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>Common Modules Source: feature/Feature.js</title>

	<!--[if lt IE 9]>
	<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.simplex.css">

</head>

<body>

<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="index.html">Common Modules</a>
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
        </button>
	</div>
	<div class="navbar-collapse collapse" id="topNavigation">
		<ul class="nav navbar-nav">
			
			<li class="dropdown">
				<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="Base.html">Base</a></li><li><a href="Event.html">Event</a></li><li><a href="Html.html">Html</a></li><li><a href="Internal.html">Internal</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li>
				</ul>
			</li>
			
			<li class="dropdown">
				<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
				<ul class="dropdown-menu ">
					<li><a href="global.html#addClass">addClass</a></li><li><a href="global.html#addListener">addListener</a></li><li><a href="global.html#arrayRemove">arrayRemove</a></li><li><a href="global.html#clear">clear</a></li><li><a href="global.html#create">create</a></li><li><a href="global.html#createHidden">createHidden</a></li><li><a href="global.html#empty">empty</a></li><li><a href="global.html#EventType">EventType</a></li><li><a href="global.html#findListener">findListener</a></li><li><a href="global.html#firstUpperToCase">firstUpperToCase</a></li><li><a href="global.html#get">get</a></li><li><a href="global.html#getChildByTagName">getChildByTagName</a></li><li><a href="global.html#getClass">getClass</a></li><li><a href="global.html#getDomEventKey">getDomEventKey</a></li><li><a href="global.html#getElementsByClassName">getElementsByClassName</a></li><li><a href="global.html#getListeners">getListeners</a></li><li><a href="global.html#getrandom">getrandom</a></li><li><a href="global.html#getStyle">getStyle</a></li><li><a href="global.html#getuuid">getuuid</a></li><li><a href="global.html#hasClass">hasClass</a></li><li><a href="global.html#isObject">isObject</a></li><li><a href="global.html#isString">isString</a></li><li><a href="global.html#layerConfigDefautls">layerConfigDefautls</a></li><li><a href="global.html#listen">listen</a></li><li><a href="global.html#listenOnce">listenOnce</a></li><li><a href="global.html#logo">logo</a></li><li><a href="global.html#OL_Style_Type">OL_Style_Type</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeClass">removeClass</a></li><li><a href="global.html#removeListener">removeListener</a></li><li><a href="global.html#removeListeners">removeListeners</a></li><li><a href="global.html#setClass">setClass</a></li><li><a href="global.html#splitWords">splitWords</a></li><li><a href="global.html#stamp">stamp</a></li><li><a href="global.html#toBack">toBack</a></li><li><a href="global.html#toFront">toFront</a></li><li><a href="global.html#trim">trim</a></li><li><a href="global.html#unListen">unListen</a></li><li><a href="global.html#unlistenAll">unlistenAll</a></li><li><a href="global.html#unListenByKey">unListenByKey</a></li><li><a href="global.html#upperFirstChart">upperFirstChart</a></li>
				</ul>
			</li>
			
		</ul>
        
            <div class="col-sm-3 col-md-3">
                <form class="navbar-form" role="search">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
                        <div class="input-group-btn">
                            <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
                        </div>
                    </div>
                </form>
            </div>
        
	</div>

</div>
</div>


<div class="container" id="toc-content">
<div class="row">

	
	<div class="col-md-12">
	
		<div id="main">
			

		<h1 class="page-title">Source: feature/Feature.js</h1>
    
<section>
    <article>
        <pre
            class="sunlight-highlight-javascript linenums">/*
 * @desc 要素相关处理
 */
import { ol } from '../constants'
import mix from '../utils/mixin'
import Style from '../style/Style'
import Layer from '../layer/Layer'

class Feature extends mix(Style, Layer) {
    constructor(map) {
        super();
        this.map = map;
        if (!this.map) {
            throw new Error('缺少地图对象！')
        }
    }

    /**
     * 通过id获取Feature
     * @param id
     * @returns {*}
     */
    getFeatureById(id) {
        let layers = this.map.getLayers(),
            feature;
        layers.forEach(layer => {
            let source = layer.getSource();
            if (source &amp;&amp; source.getFeatureById) {
                feature = source.getFeatureById(id);
            }
        });
        return feature;
    }

    /**
     * 通过id和layerName获取Feature
     * （若在当前layerName查不到，则查询全部图层）
     * @param id
     * @param layerName
     * @returns {*}
     */
    getFeatureById2LayerName(id, layerName) {
        let feature = null;
        if (!!layerName) {
            let layer = this.getLayerByName(layerName);
            if (layer &amp;&amp; layer instanceof ol.layer.Vector) {
                feature = layer.getSource().getFeatureById(id)
            }
        }
        if (!feature || !(feature instanceof ol.Feature)) {
            feature = this.getFeatureById(id);
        }
        return feature;
    }

    /**
     * 从属性信息中获取空间信息
     * @param point
     * @returns {*}
     * @private
     */
    _getGeometryFromPoint(point) {
        let geometry = null;
        if (point instanceof ol.geom.Geometry) {
            geometry = point;
        } else if (Array.isArray(point.geometry)) {
            geometry = new ol.geom.Point(point.geometry);
        } else {
            geometry = new ol.format.WKT().readGeometry(point.geometry);
        }
        return geometry;
    }

    /**
     * 获取当前范围
     * @param multiFeatures
     * @private
     */
    _getExtent(multiFeatures) {
        let extent = multiFeatures.getExtent();
        let bExtent = true;
        for (let m = 0; m &lt; 4; m++) {
            if (extent[m] == Infinity || extent[m] == NaN) {
                bExtent = false;
                break;
            }
        }
        if (bExtent) {
            this.zoomToExtent(extent, true);
        }
        return extent;
    }

    /**
     * 调整当前要素范围
     * @param extent
     * @returns {*}
     */
    adjustExtent(extent) {
        if (this.map) {
            let width = ol.extent.getWidth(extent);
            let height = ol.extent.getHeight(extent);
            let adjust = 0.2;
            if (width &lt; 0.05) {
                let bleft = ol.extent.getBottomLeft(extent); //获取xmin,ymin
                let tright = ol.extent.getTopRight(extent); //获取xmax,ymax
                let xmin = bleft[0] - adjust;
                let ymin = bleft[1] - adjust;
                let xmax = tright[0] + adjust;
                let ymax = tright[1] + adjust;
                extent = ol.extent.buffer(extent, adjust);
            }
            return extent;
        }
    }

    /**
     * 缩放到当前范围
     * @param extent
     * @param isanimation
     * @param duration
     */
    zoomToExtent(extent, isanimation, duration) {
        if (this.map) {
            let view = this.map.getView();
            let size = this.map.getSize();
            /**
             *  @type {ol.Coordinate} center The center of the view.
             */
            let center = ol.extent.getCenter(extent);
            if (!isanimation) {
                view.fit(extent, size, {
                    padding: [350, 200, 200, 350]
                });
                view.setCenter(center);
            } else {
                if (!duration) {
                    duration = 2000;
                    view.animate({
                        center: center,
                        duration: duration
                    });
                    view.fit(extent, size);
                }
            }
        }
    };

    /**
     * 判断点是否在视图内，如果不在地图将自动平移
     */
    movePointToView(coordinate) {
        if (this.map) {
            let extent = this.getMapCurrentExtent();
            if (!(ol.extent.containsXY(extent, coordinate[0], coordinate[1]))) {
                this.map.getView().setCenter([coordinate[0], coordinate[1]]);
            }
        }
    }

    /**
     * 获取当前地图的范围
     * @returns {ol.Extent}
     */
    getMapCurrentExtent() {
        if (this.map) {
            return this.map.getView().calculateExtent(this.map.getSize());
        }
    };

    /**
     * 添加单点
     * @param point
     * @param params
     * @returns {ol.Feature|ol.format.Feature|*|ol.render.Feature|Feature}
     */
    addPoint(point, params) {
        let geometry = this._getGeometryFromPoint(point);
        let style = this.getStyleByPoint(point['attributes']);
        let feature = new ol.Feature({
            geometry: geometry,
            params: params
        });
        feature.setStyle(style);
        if (point['attributes'] &amp;&amp; (point['attributes']['id'] || point['attributes']['ID'])) {
            // let id = (point['attributes']['id'] ? point['attributes']['id'] : (point['attributes']['ID'] ? point['attributes']['ID'] : params['id']));
            let id = (point.attributes['id'] || point.attributes['ID'] || params['id']);
            feature.setId(id);
            feature.setProperties(point['attributes']);
        }
        if (params['zoomToExtent']) {
            let coordinate = geometry.getCoordinates();
            // extent = this.adjustExtent(extent);
            this.movePointToView(coordinate);
        }
        if (params['layerName']) {
            let layer = this.creatVectorLayer(params['layerName'], {
                create: true
            });
            layer.getSource().addFeature(feature);
        }
        return feature;
    }

    /**
     * 添加多个点
     * @param points
     * @param params
     */
    addPoints(points, params) {
        if (points &amp;&amp; Array.isArray(points)) {
            let multiPoint = new ol.geom.MultiPoint([]),
                change = false;
            if (params['zoomToExtent']) {
                params['zoomToExtent'] = !params['zoomToExtent'];
                change = true;
            };
            for (let i = 0; i &lt; points.length; i++) {
                let pointFeat = this.addPoint(points[i], params);
                multiPoint.appendPoint(pointFeat.getGeometry());
            }
            if (change) {
                this._getExtent(multiPoint);
            }
        }
    }

    /**
     * 添加线要素
     * @param line
     * @param params
     * @returns {*}
     */
    addPolyline(line, params) {
        let linefeature = null;
        if (line.geometry.hasOwnProperty('paths')) {
            let feat = {
                'type': 'Feature',
                'geometry': {
                    'type': 'MultiLineString',
                    'coordinates': line.geometry.paths
                }
            };
            linefeature = (new ol.format.GeoJSON()).readFeature(feat);
        } else {
            linefeature = new ol.Feature({
                geometry: new ol.format.WKT().readGeometry(line.geometry)
            });
        }
        let style = this.getStyleByLine(line['attributes']);
        let extent = linefeature.getGeometry().getExtent();
        if (style &amp;&amp; linefeature) {
            linefeature.setStyle(style);
        }
        if (line['attributes'] &amp;&amp; (line.attributes['ID'] || line.attributes['id'])) {
            // let id = (line['attributes']['id'] ? line['attributes']['id'] : (line['attributes']['ID'] ? line['attributes']['ID'] : params['id']));
            let id = (line.attributes['id'] || line.attributes['ID'] || params['id']);
            linefeature.setId(id);
            linefeature.setProperties(line.attributes);
        }
        if (params['zoomToExtent']) {
            this.zoomToExtent(extent, true);
        }
        if (params['layerName']) {
            let layer = this.creatVectorLayer(params['layerName'], {
                create: true
            });
            layer.getSource().addFeature(linefeature);
        }
        return linefeature;
    }

    /**
     * 添加多条线要素
     * @param lines
     * @param params
     */
    addPolylines(lines, params) {
        if (lines &amp;&amp; Array.isArray(lines)) {
            let MultiLine = new ol.geom.MultiLineString([]),
                change = false;
            if (params['zoomToExtent']) {
                params['zoomToExtent'] = !params['zoomToExtent'];
                change = true;
            };
            for (let i = 0; i &lt; lines.length; i++) {
                let polyLine = this.addPolyline(lines[i], params);
                MultiLine.appendLineString(polyLine.getGeometry());
            }
            if (change) {
                this._getExtent(MultiLine);
            }
        }
    }

    /**
     * 添加面要素
     * @param polygon
     * @param params
     * @returns {ol.render.Feature|ol.format.Feature|Feature|*|ol.Feature}
     */
    addPolygon(polygon, params) {
        if (polygon &amp;&amp; polygon['geometry']) {
            let polygonFeature = new ol.Feature({
                geometry: new ol.format.WKT().readGeometry(polygon.geometry)
            });
            let style = this.getStyleByPolygon(polygon['attributes']);
            let extent = polygonFeature.getGeometry().getExtent();
            if (style &amp;&amp; polygonFeature) {
                polygonFeature.setStyle(style);
            }
            if (polygon['attributes'] &amp;&amp; (polygon.attributes['ID'] || polygon.attributes['id'])) {
                let id = (polygon.attributes['id'] || polygon.attributes['ID'] || params['id']);
                polygonFeature.setId(id);
                polygonFeature.setProperties(polygon.attributes);
            }
            if (params['zoomToExtent']) {
                this.zoomToExtent(extent, true);
            }
            if (params['layerName']) {
                let layer = this.creatVectorLayer(params['layerName'], {
                    create: true
                });
                layer.getSource().addFeature(polygonFeature);
            }
            return polygonFeature;
        } else {
            console.info('传入的数据不标准！')
        }
    }

    /**
     * 添加多个面
     * @param polygons
     * @param params
     */
    addPolygons(polygons, params) {
        if (polygons &amp;&amp; Array.isArray(polygons)) {
            let MultiPolygon = new ol.geom.MultiPolygon([]),
                change = false;
            if (params['zoomToExtent']) {
                params['zoomToExtent'] = !params['zoomToExtent'];
                change = true;
            };
            for (let i = 0; i &lt; polygons.length; i++) {
                let polygon = this.addPolyline(polygons[i], params);
                MultiPolygon.appendPolygon(polygon.getGeometry());
            }
            if (change) {
                this._getExtent(MultiPolygon);
            }
        }
    }

    /**
     * 通过图层名移除要素
     * @param layerName
     */
    removeFeatureByLayerName(layerName) {
        try {
            let layer = this.getLayerByLayerName(layerName);
            if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource()) {
                layer.getSource().clear();
            }
        } catch (e) {
            console.log(e)
        }
    }

    /**
     * 移除多个图层的要素
     * @param layerNames &lt;Array>
     */
    removeFeatureByLayerNames(layerNames) {
        if (layerNames &amp;&amp; Array.isArray(layerNames) &amp;&amp; layerNames.length > 0) {
            layerNames.forEach(item => {
                this.removeFeatureByLayerName(item);
            })
        } else {
            console.info('id为空或者不是数组！')
        }
    }

    /**
     * 移除当前要素
     * @param feature
     */
    removeFeature(feature) {
        if (feature &amp;&amp; feature instanceof ol.Feature) {
            let tragetLayer = this.getLayerByFeatuer(feature);
            if (tragetLayer) {
                let source = tragetLayer.getSource();
                if (source &amp;&amp; source.removeFeature) {
                    source.removeFeature(feature);
                }
            }
        } else {
            throw new Error('传入的不是要素!')
        }
    }

    /**
     * 通过id移除要素
     * @param id
     * @param layerName
     */
    removeFeatureById(id, layerName) {
        if (this.map &amp;&amp; id) {
            if (layerName) {
                let layer = this.getLayerByLayerName(layerName);
                if (layer) {
                    let feature = layer.getSource().getFeatureById(id);
                    if (feature &amp;&amp; feature instanceof ol.Feature) {
                        layer.getSource().removeFeature(feature);
                    }
                }
            } else {
                let layers = this.map.getLayers().getArray();
                layers.forEach(layer => {
                    if (layer &amp;&amp; layer instanceof ol.layer.Vector &amp;&amp; layer.getSource()) {
                        let feature = layer.getSource().getFeatureById(id);
                        if (feature &amp;&amp; feature instanceof ol.Feature) {
                            layer.getSource().removeFeature(feature);
                        }
                    }
                });
            }
        }
    }

    /**
     * 移除多个要素
     * @param ids
     * @param layerName
     */
    removeFeatureByIds(ids, layerName) {
        if (ids &amp;&amp; Array.isArray(ids) &amp;&amp; ids.length > 0) {
            ids.forEach(item => {
                this.removeFeatureById(item, layerName);
            })
        } else {
            console.info('id为空或者不是数组！')
        }
    }
}

export  {Feature}</pre>
    </article>
</section>





		</div>
	</div>

	<div class="clearfix"></div>

	

</div>
</div>


    <div class="modal fade" id="searchResults">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Search results</h4>
          </div>
          <div class="modal-body"></div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>


<footer>


	<span class="copyright">
	https://lzw.me.
	</span>

<span class="jsdoc-message">
	Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a>
	
		on Sun Aug 12th 2018
	
	using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>.
</span>
</footer>

<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/toc.js"></script>

    <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script>


<script>
$( function () {
	$( "[id*='$']" ).each( function () {
		var $this = $( this );

		$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
	} );

	$( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () {
		var $this = $( this );

		var example = $this.find( "code" );
		exampleText = example.html();
		var lang = /{@lang (.*?)}/.exec( exampleText );
		if ( lang && lang[1] ) {
			exampleText = exampleText.replace( lang[0], "" );
			example.html( exampleText );
			lang = lang[1];
		} else {
			var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/);
			lang = langClassMatch ? langClassMatch[1] : "javascript";
		}

		if ( lang ) {

			$this
			.addClass( "sunlight-highlight-" + lang )
			.addClass( "linenums" )
			.html( example.html() );

		}
	} );

	Sunlight.highlightAll( {
		lineNumbers : true,
		showMenu : true,
		enableDoclinks : true
	} );

	$.catchAnchorLinks( {
        navbarOffset: 10
	} );
	$( "#toc" ).toc( {
		anchorName  : function ( i, heading, prefix ) {
			return $( heading ).attr( "id" ) || ( prefix + i );
		},
		selectors   : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4",
		showAndHide : false,
		smoothScrolling: true
	} );

	$( "#main span[id^='toc']" ).addClass( "toc-shim" );
	$( '.dropdown-toggle' ).dropdown();

    $( "table" ).each( function () {
      var $this = $( this );
      $this.addClass('table');
    } );

} );
</script>



<!--Navigation and Symbol Display-->


<!--Google Analytics-->



    <script type="text/javascript">
        $(document).ready(function() {
            SearcherDisplay.init();
        });
    </script>


</body>
</html>
